import {createStore} from 'vuex'
import {ElMessage} from "element-plus";
import {getAllPatientInfo} from "../api/display";
import { findByRoomBed, arrInitialize } from '../api/display';

const store= createStore({
    state: {
        tagsList: [],
        collapse: false,
        //#region
        user: {
            name: 'piggy',
            img: 'src/assets/img/avatar.jpg'
        },
        //病人列表
        patientData:[],
        allRoomBed:{},
        roomBedList:[],
        infoData : [
            {name: '在住病人', value: 0,},//数组初值
            {name: '今日入院', value: 0,},
            {name: '手术', value: 0,},
            {name: '病重', value: 0,},
            {name: '男', value: 0,},//4
            {name: '女', value: 0,},//5
            {name: '老人', value: 0,},//6
            {name: '婴儿', value: 0,}//7
        ],
        levelData : [
            {
            name: '一级护理',
            color: 'rgb(245, 108, 108)',//展示
            count: 0
            },
            {
                name: '二级护理',
                color: 'rgb(230, 162, 60)',
                count: 0
            },
            {
                name: '三级护理',
                color: 'rgb(64, 158, 255)',
                count: 0
            },
        ],
        dayData : [
            {
                name: '<1个月',
                value: 0,
            },
            {
                name: '1-3个月',
                value: 0,
            },
            {
                name: '>3个月',
                value: 0,
            },
        ],
        //#endregion
        //MQ相关
        mqMesgList: [],
        nurseCallVisible:false,
        ws:null,
    },
    mutations: {
        delTagsItem(state, data) {
            state
                .tagsList
                .splice(data.index, 1);
        },
        setTagsItem(state, data) {
            state
                .tagsList
                .push(data)
        },
        clearTags(state) {
            state.tagsList = []
        },
        closeTagsOther(state, data) {
            state.tagsList = data;
        },
        closeCurrentTag(state, data) {
            for (let i = 0, len = state.tagsList.length; i < len; i++) {
                const item = state.tagsList[i];
                if (item.path === data.$route.fullPath) {
                    if (i < len - 1) {
                        data
                            .$router
                            .push(state.tagsList[i + 1].path);
                    } else if (i > 0) {
                        data
                            .$router
                            .push(state.tagsList[i - 1].path);
                    } else {
                        data
                            .$router
                            .push("/");
                    }
                    state
                        .tagsList
                        .splice(i, 1);
                    break;
                }
            }
        },
        // 侧边栏折叠
        handleCollapse(state, data) {
            state.collapse = data;
        },
        //更新病人、病房数据
        refresh (state) {
            let tempData=[];
            let tempRoomBedList = [];
            let tempInfo = [
                {name: '在住病人', value: 0,},//数组初值
                {name: '今日入院', value: 0,},//1
                {name: '手术', value: 0,},//2
                {name: '病重', value: 0,},//3

                {name: '男', value: 0,},//4
                {name: '女', value: 0,},//5

                {name: '老人', value: 0,},//6
                {name: '婴儿', value: 0,},//7
                {name: '中年', value: 0,},//8
                {name: '青年', value: 0,},//9
                {name: '少年', value: 0,},//10
            ]
            let tempLevel = [
                    {
                        name: '一级护理',
                        color: 'rgb(245, 108, 108)',//展示
                        count: 0
                    },
                    {
                        name: '二级护理',
                        color: 'rgb(230, 162, 60)',
                        count: 0
                    },
                    {
                        name: '三级护理',
                        color: 'rgb(64, 158, 255)',
                        count: 0
                    },]
            let tempDay = [
                {
                    name: '<1个月',
                    value: 0,
                },
                {
                    name: '1-3个月',
                    value: 0,
                },
                {
                    name: '>3个月',
                    value: 0,
                },]        
            //获取病房列表
            getAllPatientInfo().then((res) => {
                if (res.code > 0) {
                    ElMessage.error('请求失败，请稍后重试！');
                } else {
                    let patientList = res.data.patientList;
                    state.allRoomBed = res.data.allRoomBed;
                    state.allRoomBed.forEach(room => {
                        let roomData = {
                          location: "",
                          count: 0,
                          bed: [],
                        };
                        roomData.location = room.location;
                        roomData.count = room.bed_count;
                        roomData.bed=findByRoomBed(room.location);
                        // console.log("=======",roomData.bed.length);
                        //  for (let i of arrInitialize(room.bed_count)) {
                        //   const p = findByRoomBed(room.location, String.fromCharCode(65 + i));
                        //   // console.log("zhaodaole===========",p);
                        //   roomData.bed=p;
                        // }
                        tempRoomBedList.push(roomData);
                      })
                    state.roomBedList =tempRoomBedList;
                    for (let i = 0; i < patientList.length; i++) {
                        for (let j = 0; j < patientList[i].length; j++) {
                            tempData.push(patientList[i][j]);
                        }
                    }
                    state.patientData=tempData;

                    //Todo:测试判空是否成功
                    //统计数据
                    const temp = tempData.filter((d) => {
                        return d.name !== null;
                    })
                    tempInfo[0].value = temp.length
                    for (let i = 0; i < tempData.length; i++) {
                        let t = tempData[i]
                        //统计今日入院
                        if (t.day == 0) tempInfo[1].value++;
                        for(let i in t.condition){
                            // console.log(i)
                            if(t.condition[i]=="术") tempInfo[2].value++;
                            if(t.condition[i]=="重") tempInfo[3].value++;
                        }
                        //统计性别
                        if (t.gender == "男") {
                            tempInfo[4].value++;
                        }
                        if (t.gender == "女") {
                            tempInfo[5].value++;
                        }
                        //统计年龄
                        if (t.age >= 60) tempInfo[6].value++;//老人
                        if (t.age < 60 && t.age >=40) tempInfo[8].value++;//中年
                        if (t.age < 40 && t.age >=18) tempInfo[9].value++;//青年
                        if (t.age < 18 && t.age >=3) tempInfo[10].value++;//少年
                        if (t.age <= 3) tempInfo[7].value++;//婴儿
                        //统计Level
                        if (t.level == 1) tempLevel[0].count++;
                        if (t.level == 2) tempLevel[1].count++;
                        if (t.level == 3) tempLevel[2].count++;
                        //统计住院时间（<=1个月/1-3个月/>3个月）
                        if(t.day <= 31) tempDay[0].value++;
                        if(t.day>31 && t.day <= 93) tempDay[1].value++;
                        if(t.day > 93) tempDay[2].value++;
                    }
                    state.infoData=tempInfo
                    state.levelData=tempLevel
                    state.dayData=tempDay
                }
            })
                .catch((e) => {
                    ElMessage.error('无法从服务端请求数据，请联系管理员！');
                });
        },
        CLOSE_NURSECALL(state){
            state.nurseCallVisible=false
        },
        //#region
        //#endregion
        //MQ相关
        SET_MQMESGLIST (state, value) {
            var index = state.mqMesgList.findIndex(item => {
                if ( item.body.role == value.body.role
                    && item.type == value.type
                    && item.body.id == value.body.id) {
                    console.log("---------收到消息---------"+item.body)
                    return true;
                    }
            })
            if(index != -1){
                console.log('重复发送求助')
            }
            if(index == -1){
                state.mqMesgList.push(value);
                let val=value
                let tmpRole=val.body.role;
                let tmpAsk=val.body.ask;
                let tmpId= val.body.id;
                let tmpType=val.type;
                //如果信号是true,要进行语音播报
                if (tmpAsk) {
                    //判断role是bed还是room
                    let zhCnRole = "";
                    if (tmpRole == "bed") {
                        zhCnRole = "床";
                    }
                    if (tmpRole == "room") {
                        zhCnRole = "";
                    }
                    //判断type是change、help、call
                    let zhCnType = "";
                    if (tmpType == "change") {
                        zhCnType = "换药";
                    }
                    if (tmpType == "help") {
                        zhCnType = "求助";
                    }
                    if (tmpType == "call") {
                        zhCnType = "呼叫";
                    }
                    //播报
                    //"id":"外科-001",将-去掉
                    // let tmpId2=tmpId.replace("-","");
                    let tmpId2 = tmpId.substring(tmpId.indexOf("-") + 1);
                    let text = tmpId2 + zhCnRole + zhCnType;
                    const msg = new SpeechSynthesisUtterance();
                    msg.text = text;
                    window.speechSynthesis.speak(msg);
                }
            }

        },
        PROCESS_MQMESGLIST (state, value) {
            var index = state.mqMesgList.findIndex(item => {
                if ( item.body.role == value.body.role
                    && item.type == value.type
                    && item.body.id == value.body.id) {
                    return true;
                }
            })
            if (index === -1) return;
            state.mqMesgList.splice(index,1)
        }
    },
    actions: {
        initData: ({ dispatch }) => dispatch('INIT_DATA'),
        sendMessage: ({ dispatch }, content) => dispatch('SEND_MESSAGE', content),
        selectSession: ({ dispatch }, id) => dispatch('SELECT_SESSION', id),
        search: ({ dispatch }, value) => dispatch('SET_FILTER_KEY', value),
        //MQ相关
        setMqMesgList: ({ dispatch }, value) => dispatch('SET_MQMESGLIST', value),
        processMqMesgList: ({ dispatch }, value) => dispatch('PROCESS_MQMESGLIST', value),
    },
    modules: {}
});

store.watch(
    // (state) => state.sessions,
    // (val) => {
    //     console.log('CHANGE: ', val);
    //     localStorage.setItem('vue-chat-session', JSON.stringify(val));
    // },
    // {
    //     deep: true
    // }
    (state) => state.mqMesgList,
    (val) => {
        console.log('CHANGEmq---: ', val);
        //打印出val数组
        // for (let i = 0; i < val.length; i++) {
        //     //如果i不等于0或者i不等于val.length-1，就continue
        //     if(i!=val.length-1) continue;
        //     let tmpRole=val[i].body.role;
        //     let tmpAsk=val[i].body.ask;
        //     let tmpId= val[i].body.id;
        //     let tmpType=val[i].type;
        //     //如果信号是true,要进行语音播报
        //     if (tmpAsk){
        //         //判断role是bed还是room
        //         let zhCnRole="";
        //         if(tmpRole=="bed"){
        //             zhCnRole="床";
        //         }
        //         if(tmpRole=="room"){
        //             zhCnRole="";
        //         }
        //         //判断type是change、help、call
        //         let zhCnType="";
        //         if(tmpType=="change"){
        //             zhCnType="换药";
        //         }
        //         if(tmpType=="help"){
        //             zhCnType="求助";
        //         }
        //         if(tmpType=="call"){
        //             zhCnType="呼叫";
        //         }
        //         //播报
        //         //"id":"外科-001",将-去掉
        //         // let tmpId2=tmpId.replace("-","");
        //         let tmpId2=tmpId.substring(tmpId.indexOf("-")+1);
        //         let text=tmpId2+zhCnRole+zhCnType;
        //         const msg = new SpeechSynthesisUtterance();
        //         msg.text = text;
        //         window.speechSynthesis.speak(msg);
        //     }

        // }
        sessionStorage.setItem('vue-chat-mqMesgList', JSON.stringify(val));
    },
    {
        deep: true
    }
);

export default store;
